package fr.babostesting.examples.stage3d.starling
{
	import com.greensock.easing.Back;
	import com.greensock.TweenMax;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.ImageDecodingPolicy;
	import flash.system.LoaderContext;
	import flash.utils.Dictionary;
	import starling.display.Image;
	import starling.display.Sprite;
	import starling.events.Event;
	import starling.textures.Texture;
	import starling.textures.TextureSmoothing;
	
	/**
	 * @author ZoulouX
	 */
	public class BatchRoot extends Sprite
	{
		protected var _twitterData		:Object;
		
		protected var _imagesURLs		:Vector.<String> 			= new Vector.<String>;
		protected var _imagesData		:Vector.<BitmapData> 		= new Vector.<BitmapData>;
		protected var _images			:Vector.<Image> 			= new Vector.<Image>;
		
		protected var _directions		:Dictionary					= new Dictionary();
		
		
		public function BatchRoot ()
		{
			var serviceURL:String = "http://search.twitter.com/search.json?q=flash&rpp=100&include_entities=true&result_type=mixed";
			
			var urlLoader:URLLoader = new URLLoader(new URLRequest(serviceURL));
			urlLoader.addEventListener(flash.events.Event.COMPLETE, dataLoadedHandler);
			trace("loading");
		}
		
		protected function dataLoadedHandler (event:flash.events.Event):void 
		{
			(event.currentTarget as URLLoader).removeEventListener(flash.events.Event.COMPLETE, dataLoadedHandler);
			
			trace("loaded");
			
			_twitterData = JSON.parse((event.currentTarget as URLLoader).data);
			
			if (_twitterData["results"] != null)
				_twitterData = _twitterData.results;
			
			const total:uint = _twitterData.length;
			
			for (var i:uint = 0; i < total; i ++)
			{
				var imageURL:String;
				
				if (_twitterData[i].profile_image_url != null)
					imageURL = _twitterData[i].profile_image_url;
				else if (_twitterData[i].user != null)
					imageURL = _twitterData[i].user.profile_image_url;
				
				_imagesURLs.push(imageURL);
			}
			
			// Commencer par charger la première image
			loadImage();
			loadImage();
			loadImage();
			
			addEventListener(starling.events.Event.ENTER_FRAME, enterFrameHandler);
		}
		
		protected function loadImage ():void
		{
			if (_imagesURLs.length > 0)
			{
				var loader:Loader = new Loader();
				var context:LoaderContext = new LoaderContext();
				context.allowCodeImport = false;
				context.imageDecodingPolicy = ImageDecodingPolicy.ON_LOAD;
				
				loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, imageLoadedHandler);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.DISK_ERROR, errorHandler);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.NETWORK_ERROR, errorHandler);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.VERIFY_ERROR, errorHandler);
				
				loader.load(new URLRequest(_imagesURLs.shift()), context);
			}
		}
		
		protected function errorHandler (event:IOErrorEvent):void
		{
			//trace(event.text);
			
			loadImage();
		}
		
		protected function imageLoadedHandler (event:flash.events.Event):void
		{
			var bitmapData:BitmapData = ((event.currentTarget as LoaderInfo).content as Bitmap).bitmapData;
			
			_imagesData.push(bitmapData);
			
			createImage(bitmapData);
			
			loadImage();
		}
		
		private function createImage (bitmapData:BitmapData):void 
		{
			var bitmap:Image = new Image(Texture.fromBitmapData(bitmapData));
			
			//bitmap.smoothing = TextureSmoothing.NONE;
			
			
			place(bitmap);
		}
		
		private function place (pDisplayObject:Image):void
		{
			_images.push(pDisplayObject);
			
			_directions[pDisplayObject] = {
				x: Math.random() * 2 - 1,
				y: Math.random() * 2 - 1,
				rotation: Math.random() * 6 - 3
			};
			
			pDisplayObject.scaleX = pDisplayObject.scaleY = 1 + Math.random();
			
			pDisplayObject.x = (stage.stageWidth - pDisplayObject.width) * Math.random();
			pDisplayObject.y = (stage.stageHeight - pDisplayObject.height) * Math.random();
			
			TweenMax.from(pDisplayObject, .5, {
				alpha: 0
			});
			TweenMax.from(pDisplayObject, .7, {
				scaleX: 0,
				scaleY: 0,
				ease: Back.easeOut
			});
			
			addChildAt(pDisplayObject, 0);
		}
		
		protected function enterFrameHandler (event:Event):void 
		{
			var total:uint = _images.length;
			var image:Image;
			
			for (var i:int = 0; i < total; i++) 
			{
				image = _images[i];
				
				if (image.x < 0)
					_directions[image].x = Math.abs(_directions[image].x);
				else if (image.x > stage.stageWidth - image.width)
					_directions[image].x = - Math.abs(_directions[image].x);
					
				if (image.y < 0)
					_directions[image].y = Math.abs(_directions[image].y);
				else if (image.y > stage.stageHeight - image.height)
					_directions[image].y = - Math.abs(_directions[image].y);
				
				_images[i].x += _directions[image].x;
				_images[i].y += _directions[image].y;
				//_images[i].rotation += _directions[image].rotation;
			}
		}
	}
}